#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/11/3 13:06
# @Author  : Crissu
# @Site    : 
# @File    : universalOP.py
# @Software: PyCharm
import os, xlrd
from ResultProcessing.configs.universalConfig import idx2classMap, class2idxMap, ywName2zhNameMap
from xlutils.copy import copy

'''
    修改文件夹名
'''
def modifyFileFoderName():
    path = "E:/sujiajie/croped_selected85_resized_tvt/val/"
    classList = os.listdir(path)
    for item in classList:
        oldName = os.path.join(path, item)
        newName = os.path.join(path, str(class2idxMap[item]))
        os.rename(oldName, newName)


def parseYWName(item):
    for key in ywName2zhNameMap:
        if ywName2zhNameMap[key] == item:
            return key
    return "null"


def getRows(name, resultList):
    for items in resultList:
        if name == items[1]:
            return items
    return []




def test():
    src = "./test.xls"
    workbook = xlrd.open_workbook(src)  # 打开工作簿
    sheets = workbook.sheet_names()  # 获取工作簿中的所有表格

    worksheet = workbook.sheet_by_name(sheets[2])  # 获取工作簿中所有表格中的的第一个表格
    getStr = str(worksheet.cell_value(0, 0))
    getList = getStr.split("、")
    # print(getList)

    resultList = list()
    for i in range(1, worksheet.nrows):
        for j in range(3):
            tmp = [int(worksheet.cell_value(i, 0)),
                   str(worksheet.cell_value(i, 1)),
                   float(worksheet.cell_value(i, 2))]
            resultList.append(tmp)
    # print(resultList)
    newResult = list()
    for item in getList:
        name = parseYWName(item)
        if name == "null":
            print("出错了_name:", item)
            break
        rows = getRows(name, resultList)
        if len(rows) == 0:
            print("出错了_rows:", name)
        newResult.append(rows)

    print(newResult)
    print(len(newResult))
    # 追加 xls
    write_excel_xls_append(src, newResult)

# 追加 xls
def write_excel_xls_append(path, value):
    row = len(value)  # 获取需要写入数据的行数
    col = len(value[0])
    workbook = xlrd.open_workbook(path)  # 打开工作簿
    sheets = workbook.sheet_names()  # 获取工作簿中的所有表格
    worksheet = workbook.sheet_by_name(sheets[2])  # 获取工作簿中所有表格中的的第一个表格
    new_workbook = copy(workbook)  # 将xlrd对象拷贝转化为xlwt对象
    new_worksheet = new_workbook.get_sheet(2)  # 获取转化后工作簿中的第一个表格
    for i in range(row):
        for j in range(col):
            new_worksheet.write(i+1, j+4, value[i][j])  # 追加写入数据，注意是从i+rows_old行开始写入
    new_workbook.save(path)  # 保存工作簿
    print("xls格式表格【追加】写入数据成功！")


if __name__ == '__main__':
    test()









